<?

$db_host = 'localhost';
$db_user = 'portals';
$db_passwd = 'unknown';
$db_name = 'portals';

$db = mysql_connect($db_host, $db_user, $db_passwd);

if (!$db) {
	header("HTTP/1.1 503 Service Unavailable");
	die("Website offline - please try later");
}

if (!mysql_select_db($db_name, $db)) {
        header("HTTP/1.1 503 Service Unavailable");
        die("Website offline - please try later.");
}


$CONF = array();

//just set this to a random string - dont share these!
$CONF['token_secret'] = "unknown";

//this is the same value as geograph uses - used for generating thumbnail urls - will have to ask geograph nicely to share it with you. 
$CONF['geograph_secret'] = 'unknown';

//use these to authenticate users against Geograph database - contact geograph for your details
$CONF['geograph_apikey'] = '';
$CONF['geograph_accesskey'] = '';
$CONF['geograph_magic'] = '';


       $DEVEL_MODE = FALSE;

####

$profiles_any = array('sphinx'=>'Full Text Query/Keywords','words'=>'Any of these words','phrase'=>'This Phrase','ids'=>'List of images','gurl'=>'In this Collection'
	,'grs'=>'List of Grid References','taken'=>'List of Taken Dates','users'=>'List of User ID\'s'
	,'title'=>'Keywords in Title only','text'=>'Keywords in Title, Description or Category only','snippet'=>'Keywords in Shared Description only','category'=>'Keywords in Category only'
);

$profiles_all = $profiles_any; unset($profiles_all['ids']);unset($profiles_all['gurl']);

$profiles_not = array('words'=>'Any of these words','phrase'=>'This Phrase','ids'=>'List of images'
	,'grs'=>'List of Grid References','taken'=>'List of Taken Dates','users'=>'List of User ID\'s'
);
#,'1'=>'','within'=>'within 2km of','2'=>'','search'=>'In this search result (first 10,000 images only)','cluster'=>'Automatic Cluster');

$profiles = $profiles_any + $profiles_not;

#ENUM: 'sphinx','words','ids','gurl','cluster','potd','last','phrase','grs','taken','users','title','text','snippet','category','','',''


	function he($in) {
		return  htmlentities($in);
	}
	function hec($in) {
		global $c;
		return  htmlentities($c[$in]);
	}
	function ehec($in) {
		echo hec($in);
	}
	
	
	function init_session()
	{
		session_start();
	
		
		
	}
	
	
	function linktoself($params,$selflink= '') {
		$a = array();
		$b = explode('?',$_SERVER['REQUEST_URI']);
		if (isset($b[1])) 
			parse_str($b[1],$a);
			
		if (isset($params['value']) && isset($a[$params['name']])) {
			if ($params['value'] == 'null') {
				unset($a[$params['name']]);
			} else {
				$a[$params['name']] = $params['value'];
			}
			
		} else {
			foreach ($params as $key => $value)
				$a[$key] = $value;
		}
		
		if (!empty($params['delete'])) {
			if (is_array($params['delete'])) {
				foreach ($params['delete'] as $del) {
					unset($a[$del]);
				}
			} else {
				unset($a[$params['delete']]);
			}
			unset($a['delete']);
		} 
		if (empty($selflink)) {
			$selflink = $_SERVER['SCRIPT_NAME'];
		} 
		if ($selflink == '/index.php') {
			$selflink = '/';
		}
		
		return htmlentities($selflink.(count($a)?("?".http_build_query($a,'','&')):''));
	}

	function gGU($gridimage_id,$user_id,$size = 'small') {
		global $CONF;
		$hash = substr(md5(intval($gridimage_id).intval($user_id).$CONF['geograph_secret']), 0, 8);
		return getGeographUrl($gridimage_id,$hash,$size);
	}
	
	function gGUc(&$c,$size = 'small') {
		global $CONF;
		$hash = substr(md5(intval($c['gridimage_id']).intval($c['user_id']).$CONF['geograph_secret']), 0, 8);
		return getGeographUrl($c['gridimage_id'],$hash,$size);
	}

	function pagesString($currentPage,$numberOfPages,$postfix = '',$extrahtml ='') {
		static $r;
		if (!empty($r))
			return($r);
	
		if ($currentPage > 1) 
			$r .= "<a href=\"".linktoself(array('page'=>$currentPage-1))."$postfix\"$extrahtml>&lt; &lt; prev</a> ";
		$start = max(1,$currentPage-5);
		$endr = min($numberOfPages+1,$currentPage+8);
	
		if ($start > 1)
			$r .= "<a href=\"".linktoself(array('page'=>1))."$postfix\"$extrahtml>1</a> ... ";
	
		for($index = $start;$index<$endr;$index++) {
			if ($index == $currentPage) 
				$r .= "<b>$index</b> "; 
			else
				$r .= "<a href=\"".linktoself(array('page'=>$index))."$postfix\"$extrahtml>$index</a> ";
		}
		if ($endr < $numberOfPages+1) 
			$r .= "... ";
	
		if ($numberOfPages > $currentPage) 
			$r .= "<a href=\"".linktoself(array('page'=>$currentPage+1))."$postfix\"$extrahtml>next &gt;&gt;</a> ";
	
		#if ( $this->fullText && empty($_GET['legacy']) && $this->currentPage < $this->numberOfPages && $this->resultCount <= $this->maxResults ) 
		#	$r .= "<a href=\"/{$this->page}?i={$this->query_id}&amp;page=".($this->numberOfPages)."$postfix\"$extrahtml>last</a> ";
		return $r;
	}	
	
	function count_active($id) {
		
		$hours = rand(12,24);
		
		$count = getOne("SELECT count FROM active_cache WHERE portal_id = $id AND updated > DATE_SUB(NOW(),INTERVAL $hours HOUR)");
	
		if ($count === 0 || $count > 0) {
			
		} else {
			$count = getOne("SELECT COUNT(*) FROM p2.gridimage{$id}_bi_view");
			
			queryExecute("REPLACE INTO active_cache SET portal_id = $id,count = $count");
			
		}
		return $count;
	}

function MakeLinks($posterText) {
	$posterText = preg_replace('/(?<!["\'>F=])(https?:\/\/[\w\.-]+\.\w{2,}\/?[\w\~\-\.\?\,=\'\/\\\+&%\$#\(\)\;\:]*)(?<!\.)(?!["\'])/e',"smarty_function_external(array('href'=>\"\$1\",'text'=>\"\$1\",'nofollow'=>1,'title'=>\"\$1\"))",$posterText);

	$posterText = preg_replace('/(?<![\/F\.])(www\.[\w\.-]+\.\w{2,}\/?[\w\~\-\.\?\,=\'\/\\\+&%\$#\(\)\;\:]*)(?<!\.)(?!["\'])/e',"smarty_function_external(array('href'=>\"http://\$1\",'text'=>\"\$1\",'nofollow'=>1,'title'=>\"\$1\"))",$posterText);

	$posterText = str_replace("/\n\n\n/",'<br/><br/>',$posterText);

	return $posterText;
}

function smarty_function_external($params)
{
	global $CONF;
  	//get params and use intelligent defaults...
  	$href=str_replace(' ','+',$params['href']);
  	if (strpos($href,'http://') !== 0)
  		$href ="http://$href";

  	if (isset($params['text']))
  		$text=$params['text'];
  	else
  		$text=$href;

  	if (isset($params['title']))
		$title=$params['title'];
	else
		$title=$text;
	
	if (isset($params['nofollow']))
		$title .= "\" rel=\"nofollow"; 	

  	if ($params['target'] == '_blank') {
  		return "<span class=\"nowrap\"><a title=\"$title\" href=\"$href\" target=\"_blank\">$text</a>".
  			"<img style=\"padding-left:2px;\" alt=\"External link\" title=\"External link - opens in a new window\" src=\"http://s0.geograph.org.uk/img/external.png\" width=\"10\" height=\"10\"/></span>";
  	} else {
  		return "<span class=\"nowrap\"><a title=\"$title\" href=\"$href\">$text</a>".
  			"<img style=\"padding-left:2px;\" alt=\"External link\" title=\"External link - shift click to open in new window\" src=\"http://s0.geograph.org.uk/img/external.png\" width=\"10\" height=\"10\"/></span>";
  	}
}
